#  -*- coding:utf-8 -*- 
"""
@ author: 罗金盛
@ time: 2024/5/27 
@ file: auto_login.py

"""
import time
import requests
import logging
from DrissionPage import WebPage
from src.config import Config, LoggerConfig
from DrissionPage.errors import ElementNotFoundError

LoggerConfig.configure_logger('log/sn-audit-report.log')

class AuditLogin:
    def __init__(self) -> None:
        self.page = WebPage('d')
        self.config = Config()
        self.url = self.config.yunma_config()['url']
        self.token = self.config.yunma_config()['token']
        self.logger = logging.getLogger('AuditLogin')

    def calculate(self, im) -> str:
        data = {
            "token": self.token,
            "type": "50101",
            "image": im,
        }
        response = requests.post(self.url, json=data, headers={'Content-Type': 'application/json'})
        return response.json()['data']['data']

    def get_login_status(self):
        """
        获取登录状态 如果是登录的 直接进行信息填入 未登录则进行自动化登录
        """
        url = "http://acc.mof.gov.cn/login_achieve/login"
        self.page.get(url)
        try:
            ele = self.page('.welcome')
            if ele:
                data = self.page.cookies(as_dict=False)
                cookies = {item['name']: item['value'] for item in data}
                time_ = str(int(time.time() * 1000))
                cookies['logintime'] = time_

                self.logger.info("目前是已经登录状态，无需再次登录！")
                return cookies
            else:
                self.logger.info('登录状态：未登录，需要登录！')
                self.login()
        except ElementNotFoundError:
            self.logger.info('登录状态：未登录，需要登录！')
            self.login()

    def login(self):
        try:
            url = "http://acc.mof.gov.cn/login_achieve/login"
            self.page.get(url)

            self.page('xpath://*[@id="loginDiv"]/div[1]/div[1]/input[1]').input(self.config.user()['user'])
            self.page.wait(0.5)
            self.page('xpath://*[@id="loginDiv"]/div[2]/div[1]/input').input(self.config.user()['password'])
            self.page.wait(0.5)

            login_code_element = self.page('#loginCode')
            login_code_image = login_code_element.get_screenshot(as_base64='png')

            login_code = self.calculate(login_code_image)
            if not login_code:
                self.logger.error("获取验证码失败")
                return None

            self.page('xpath://*[@id="loginDiv"]/div[3]/div[1]/input').input(login_code)
            self.page.wait(2)

            btn_submit = self.page('xpath://*[@id="loginDiv"]/div[4]')
            btn_submit.click.at(offset_x=100)  # 向右偏移100px 直接点击无法登录 做出适当偏移就可以正常登录
            self.page.wait(2)

            data = self.page.cookies(as_dict=False)
            cookies = {item['name']: item['value'] for item in data}
            time_ = str(int(time.time() * 1000))
            cookies['logintime'] = time_
            self.logger.info("登录成功")
            return cookies

        except Exception as e:
            self.logger.error(f"登录失败: {e}")
            return None


if __name__ == '__main__':
    audit_login = AuditLogin()
    cookies = audit_login.get_login_status()
    if cookies:
        print(cookies)
